import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Upload,Button, Select, notification, InputNumber, Card } from 'antd';
import "./form.less"

import { trim } from "../../utils/tool"
class UploadGroupRoad extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            fileList: [],
            typelist: [],
            rfilelist: [],
            uploadShow: true,
            directary: "",
            road: null,
            loading:false,
            groupName: 'unknow'
        }
        this.onConfirm = this.onConfirm.bind(this);
        this.reset = this.reset.bind(this)
        this.getData = this.getData.bind(this)
        this.toUploadRoad = this.toUploadRoad.bind(this)
        this.validate = this.validate.bind(this)
        this.warn=this.warn.bind(this)
    }
    async reset() {
        let { form } = this.props;
        await this.setState({
            uploadShow: false
        })
        let values = form.getFieldsValue()

        for (const key in values) {
            if (values.hasOwnProperty(key)) {
                let ks = key.toLowerCase()
                if (ks != "roadtype" && ks != "projectid" && ks != "id") {
                    values[key] = null
                }
            }
        }
        form.setFieldsValue(values)
        this.setState({
            fileList: [],
            uploadShow: true
        })
    }
    onConfirm(params = {}) {
        let formdata = new FormData()
        const { extra,current,form,updateRoad,loadRefProjectRoads,treeContext,uploadFiles} = this.props;
        return new Promise((resolve, reject) => {
            form.validateFields((error, values) => {
                if (!error) {
                    if (extra && extra.code == "edit") {
                       updateRoad(values, async res => {
                            let res2 = await loadRefProjectRoads({ projectId:current.id })
                            if (res2 && res2.length) {
                                const len = res2.length
                                for (let i = 0; i < len; i++) {
                                    let item = res2[i];
                                    item.title = '道路 : ' + item.name;
                                    item.key = 'group_road_unit' + item.id;
                                    item.eventType = 'group_road_unit'
                                    item.eventKey = 'group_road_unit'
                                    item.checkable = false
                                    if (values.id == item.id) {
                                      treeContext.updateTreeNodeSelf('group_road_unit' + values.id, item)
                                    }
                                }

                            }
                            resolve(`路线${values.name}更新成功!`)
                        }, err => {
                            reject()
                        })
                    } else {
                        values = trim(values)
                        values.file = values.file.fileList.map(item => item.originFileObj)
                        const len2 = values.file.length
                        for (let i = 0; i < len2; i++) {
                            const item = values.file[i];
                            formdata.append('files', item)
                        }
                        formdata.append('fileDir', this.state.directary)
                        for (const key in values) {
                            if (values.hasOwnProperty(key)) {
                                const item = values[key];
                                if (key != 'file') {
                                    formdata.append(key, item)
                                }

                            }
                        }
                       uploadFiles(
                        formdata,
                            async (res) => {
                                if (res != "020162") {
                                    this.reset()
                                }
                                resolve(`路线${values.name}添加成功!`)
                                let res2 = await loadRefProjectRoads({ projectId: current.id })
                                if (res2 && res2.length) {
                                    const len3 = res2.length
                                    for (let i = 0; i < len3; i++) {
                                        let item = res2[i];
                                        item.title = '道路 : ' + item.name;
                                        item.key = 'group_road_unit' + item.id;
                                        item.eventType = 'group_road_unit'
                                        item.eventKey = 'group_road_unit'
                                        item.checkable = false
                                    }
                                   treeContext.updateTreeNode('groupRoads' + current.id, res2)
                                }

                                if (params.onSuccess) {
                                    params.onSuccess(res);
                                }
                            },
                            (error) => {
                                reject()
                                if (params.onError) {
                                    params.onError(error);
                                }
                            }
                        );
                    }

                } else {
                    reject()
                }
            })
        })
    }
    warn(message){
        this.st2=setTimeout(()=>{
            clearTimeout(this.st2)
            notification.warn({ message})
        },10)
    }
    validate(e) {
        this.setState({
            loading:true
        })
        if(this.st2){
            clearTimeout(this.st2)
        }
        return new Promise((resolve, reject) => {
            let { fileList } = this.state;
            this.setState({
                loading:false,
            })
            if (e.file.originFileObj.webkitRelativePath.split('/').length > 2) {
                this.warn("此操作上传的文件夹中含有其他文件夹，请移除内部文件夹!")
                reject()
                return;
            }
            if (new RegExp(/\.php|\.exe|\.cmd|\.bat|\.java/).test(e.file.originFileObj.webkitRelativePath)) {
                this.warn("文件非法!")
                reject()
                return;
            }
            fileList.push(e.file)
            this.setState({
                
                fileList: fileList
            })
            resolve()
        })
    }
    componentWillUnmount() {
        if (this.st2) {
            clearTimeout(this.st2)
        }
    }
    componentDidMount() {
        const {dictlist,onLoaded,extra}=this.props;
        if (onLoaded) {
            onLoaded(this);
        }
        if (dictlist) {
            this.setState({
                typelist: dictlist.filter(item => item.dictType == "road_type")
            })
        }
        if (extra &&extra.code == "edit") {
            this.getData(extra.roadId)
        }
    }
    async getData(id) {
        const { current } = this.props;
        let res = await this.props.queryProjectRoads({ projectId: current.id })
        let res2 = await this.props.RoadlineOriginData({ roadlineId: id })
        const road = res.find(item => item.id == id)
        this.setState({
            road,
            rfilelist: res2
        })
    }
    toUploadRoad(e, item) {
        e.preventDefault();
        this.props.goInnerPage(null, 'OtherLines' + item.attrName, item.attrName, { roadId: item.roadlineId })
    }
    render() {
        const {
            form = {},
            mode = 'add',
            extra,
            current
        } = this.props;
        const { getFieldDecorator, setFieldsValue } = form;
        const { directary, typelist, uploadShow, fileList, rfilelist, road,loading } = this.state
        return (
            <Form
                style={{ marginTop: "30px" }}
                labelAlign="right"

                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
            >

                {uploadShow && (!extra || (extra && extra.code != "edit")) ?
                    <Form.Item labelCol={{ span: 3 }}
                        wrapperCol={{ span: 21 }} style={{ width: "83%", overflow: "hidden" }} label='上传线路'>
                        {getFieldDecorator('file', {
                            rules: [
                                { required: true, message: '上传线路' }
                            ]
                        })(
                            <Upload
                                accept="*"
                                directory
                                multiple
                                customRequest={(e) => {
                                }}
                                fileList={fileList}
                                beforeUpload={async e => {
                                    if (fileList && fileList.length) {
                                        await this.setState({
                                            fileList: []
                                        })

                                    }

                                }}
                                onRemove={file=>{
                                    const index = this.state.fileList.indexOf(file);
                                    this.state.fileList.splice(index, 1);
                                    this.setState({
                                        fileList:[...this.state.fileList]
                                    })
                                  }}
                                onChange={async (e) => {
                                    if(this.st2){
                                        clearTimeout(this.st2)
                                    }
                                    await this.validate(e)

                                    if (e.file.originFileObj) {
                                        e.file.status = "done"
                                        this.setState({
                                          
                                            directary: e.file.originFileObj.webkitRelativePath.split('/')[0]
                                        })
                                        setFieldsValue({
                                            name: e.file.originFileObj.webkitRelativePath.split('/')[0]
                                        })
                                    }

                                }}
                            >
                                <Button loading={loading} className="upload" style={{ width: '120px', height: '120px', borderRadius: '0.2em', lineHeight: '120px', color: '#888', border: 'dashed 0.5px #d8d8d8', cursor: 'pointer', textAlign: 'center' }}>
                                上传路线文件
                                </Button>
                            </Upload>
                        )}
                    </Form.Item> : null}
                {extra && extra.code == "edit" ? <Form.Item labelCol={{ span: 3 }}
                    wrapperCol={{ span: 21 }} style={{ width: "85%", overflow: "hidden" }} label='线路名称'>
                    {getFieldDecorator('slist', {
                        rules: [
                            { required: false, message: '上传线路' }
                        ]
                    })(

                        <div>
                            {
                                rfilelist && rfilelist.length ? rfilelist.map((item, index) => {
                                    return (<div className="roadFile" onClick={e => this.toUploadRoad(e, item)} key={'filename' + index}>{item.fileName}</div>)
                                }) : null
                            }
                        </div>

                    )}
                </Form.Item> : undefined}
                <Form.Item className="half" label='路线名称'>
                    {getFieldDecorator('name', {
                        rules: [
                            { required: true, message: '路线名称' }
                        ],
                        initialValue: road ? road.name : directary
                    })(
                        <Input placeholder="请输入路线名称" />
                    )}
                </Form.Item>

                <Form.Item className="half" label='文件类型'>
                    {getFieldDecorator('roadType', {
                        rules: [
                            { required: true, message: '类型' }
                        ],
                        initialValue: 9
                    })(
                        <Select disabled>
                            {
                                typelist.map((item, index) => {
                                    return <Select.Option key={item.id} value={item.id} >{item.dictLabel}</Select.Option>
                                })
                            }

                        </Select>
                    )}
                </Form.Item>

                <Form.Item className="half" label='路基宽度(m)'>
                    {getFieldDecorator('width', {
                        rules: [
                            { required: true, message: '路基宽度' }
                        ],
                        initialValue: road ? road.width : undefined
                    })(
                        <InputNumber type="number" placeholder="请输入路基宽度"></InputNumber>
                    )}
                </Form.Item>
                <div className="half"></div>
                {/* <Form.Item className="half" label='步长(m)'>
                        {getFieldDecorator('step', {
                            rules: [
                                { required: true, message: '步长' }
                            ]
                        })(
                            <InputNumber type="number" placeholder="请输入步长"></InputNumber>
                        )}
                    </Form.Item> */}


                <Form.Item style={mode=="edit"?{display:'none'}:{}} className="hide half" label='ID'>
                    {getFieldDecorator('projectId', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: current.id
                    })(
                        <Input />
                    )}
                </Form.Item>
                <Form.Item style={mode=="edit"?{display:'none'}:{}} className="hide half" label='ID'>
                    {getFieldDecorator('id', {
                        rules: [
                            { required: extra && extra.code == 'edit' ? true : false, message: '必填' }
                        ],
                        initialValue: extra && extra.code == 'edit' ? extra.roadId : undefined
                    })(
                        <Input />
                    )}
                </Form.Item>
            </Form>
        );
    }
}

export default connect(
    ({ project: { current } }) => ({ current }),
    dispatch => ({
        uploadFiles: (values, onSuccess, onError) => dispatch({
            type: 'refRoads/uploadFiles',
            payload: {
                values,
                onSuccess,
                onError

            }
        }),
        updateRoad: (values, onSuccess, onError) => dispatch({
            type: 'refRoads/updateRoad',
            payload: {
                values,
                onSuccess,
                onError

            }
        }),
        RoadlineOriginData: (values) => dispatch({
            type: 'refRoads/RoadlineOriginData',
            payload: values
        }),
        queryProjectRoads: (values) => dispatch({
            type: 'refRoads/queryProjectRoads',
            payload: values
        }),
        loadRefProjectRoads: (values) => dispatch({
            type: 'refRoads/loadRefProjectRoads',
            payload: values
        }),
    })
)(Form.create('UploadGroupRoad', {

})(UploadGroupRoad));